package cn.infrabase.crypto;

import cn.infrabase.crypto.digest.DigestAlgorithm;
import cn.infrabase.crypto.digest.DigestAlgorithmNotSupportException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;

/**
 * 安全工具类。
 *
 * @author Weimin Gao
 * @since 1.0.0
 **/
public class SecurityUtils {

    /**
     * 创建消息摘要对象。
     *
     * @param algorithm 摘要算法枚举。
     * @return 消息摘要对象。
     */
    public static MessageDigest createMessageDigest(DigestAlgorithm algorithm) {
        final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider();
        MessageDigest digest;
        String code = algorithm.code();
        try {
            digest = (null == provider) ? MessageDigest.getInstance(code) : MessageDigest.getInstance(code, provider);
        } catch (NoSuchAlgorithmException e) {
            throw new DigestAlgorithmNotSupportException(code);
        }
        return digest;
    }
}
